package jnpf.zcasset.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.model.dictionarytype.DictionaryTypeSelectVO;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.util.*;
import jnpf.zcasset.entity.ZcAssetAreaEntity;
import jnpf.zcasset.entity.ZcAssetImageEntity;
import jnpf.zcasset.entity.ZcAssetInfoEntity;
import jnpf.zcasset.entity.ZcAssetWarrantEntity;
import jnpf.zcasset.mapper.ZcAssetInfoMapper;
import jnpf.zcasset.model.zcassetinfo.ZcAssetInfoForm;
import jnpf.zcasset.model.zcassetinfo.ZcAssetInfoPagination;
import jnpf.zcasset.service.ZcAssetAreaService;
import jnpf.zcasset.service.ZcAssetImageService;
import jnpf.zcasset.service.ZcAssetInfoService;
import jnpf.zcasset.service.ZcAssetWarrantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 资产管理
 * 版本： V3.2.0
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期：
 */
@Service
public class ZcAssetInfoServiceImpl extends ServiceImpl<ZcAssetInfoMapper, ZcAssetInfoEntity> implements ZcAssetInfoService {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;

    @Autowired
    private ZcAssetWarrantService zcAssetWarrantService;
    @Autowired
    private ZcAssetAreaService zcAssetAreaService;
    @Autowired
    private ZcAssetImageService zcAssetImageService;

    @Override
    public List<ZcAssetInfoEntity> getList(ZcAssetInfoPagination zcAssetInfoPagination) {
        return getTypeList(zcAssetInfoPagination, zcAssetInfoPagination.getDataType());
    }

    @Override
    public List<ZcAssetInfoEntity> getTypeList(ZcAssetInfoPagination zcAssetInfoPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int zcAssetAreaNum = 0;
        QueryWrapper<ZcAssetAreaEntity> zcAssetAreaQueryWrapper = new QueryWrapper<>();
        int zcAssetImageNum = 0;
        QueryWrapper<ZcAssetImageEntity> zcAssetImageQueryWrapper = new QueryWrapper<>();
        int zcAssetInfoNum = 0;
        QueryWrapper<ZcAssetInfoEntity> zcAssetInfoQueryWrapper = new QueryWrapper<>();
        int zcAssetWarrantNum = 0;
        QueryWrapper<ZcAssetWarrantEntity> zcAssetWarrantQueryWrapper = new QueryWrapper<>();
        long zcAssetAreacount = zcAssetAreaService.count();
        long zcAssetImagecount = zcAssetImageService.count();
        long zcAssetWarrantcount = zcAssetWarrantService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcAssetInfoPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            int zcAssetAreaNum1 = 0;
            QueryWrapper<ZcAssetAreaEntity> zcAssetAreaSuperWrapper = new QueryWrapper<>();
            zcAssetAreaNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcAssetAreaSuperWrapper, superQueryList, matchLogic, "zcAssetArea")
                    , new ZcAssetAreaEntity(), zcAssetAreaNum1);
            if (zcAssetAreaNum1 > 0 && zcAssetAreacount > 0) {
                List<String> zcAssetAreaList = zcAssetAreaService.list(zcAssetAreaSuperWrapper).stream().map(ZcAssetAreaEntity::getAssetId).collect(Collectors.toList());
                allSuperList.addAll(zcAssetAreaList);
                intersectionSuperList.add(zcAssetAreaList);
            }
            int zcAssetImageNum1 = 0;
            QueryWrapper<ZcAssetImageEntity> zcAssetImageSuperWrapper = new QueryWrapper<>();
            zcAssetImageNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcAssetImageSuperWrapper, superQueryList, matchLogic, "zcAssetImage")
                    , new ZcAssetImageEntity(), zcAssetImageNum1);
            if (zcAssetImageNum1 > 0 && zcAssetImagecount > 0) {
                List<String> zcAssetImageList = zcAssetImageService.list(zcAssetImageSuperWrapper).stream().map(ZcAssetImageEntity::getAssetId).collect(Collectors.toList());
                allSuperList.addAll(zcAssetImageList);
                intersectionSuperList.add(zcAssetImageList);
            }
            int zcAssetInfoNum1 = 0;
            QueryWrapper<ZcAssetInfoEntity> zcAssetInfoSuperWrapper = new QueryWrapper<>();
            zcAssetInfoNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcAssetInfoSuperWrapper, superQueryList, matchLogic, "zcAssetInfo")
                    , new ZcAssetInfoEntity(), zcAssetInfoNum1);
            if (zcAssetInfoNum1 > 0) {
                List<String> zcAssetInfoList = this.list(zcAssetInfoSuperWrapper).stream().map(ZcAssetInfoEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(zcAssetInfoList);
                intersectionSuperList.add(zcAssetInfoList);
            }
            int zcAssetWarrantNum1 = 0;
            QueryWrapper<ZcAssetWarrantEntity> zcAssetWarrantSuperWrapper = new QueryWrapper<>();
            zcAssetWarrantNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcAssetWarrantSuperWrapper, superQueryList, matchLogic, "zcAssetWarrant")
                    , new ZcAssetWarrantEntity(), zcAssetWarrantNum1);
            if (zcAssetWarrantNum1 > 0 && zcAssetWarrantcount > 0) {
                List<String> zcAssetWarrantList = zcAssetWarrantService.list(zcAssetWarrantSuperWrapper).stream().map(ZcAssetWarrantEntity::getAssetId).collect(Collectors.toList());
                allSuperList.addAll(zcAssetWarrantList);
                intersectionSuperList.add(zcAssetWarrantList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcAssetAreaObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetAreaQueryWrapper, zcAssetInfoPagination.getMenuId(), "zc_asset_area"));
                if (ObjectUtil.isEmpty(zcAssetAreaObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetAreaQueryWrapper = (QueryWrapper<ZcAssetAreaEntity>) zcAssetAreaObj;
                    zcAssetAreaNum++;
                }
                Object zcAssetImageObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetImageQueryWrapper, zcAssetInfoPagination.getMenuId(), "zc_asset_image"));
                if (ObjectUtil.isEmpty(zcAssetImageObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetImageQueryWrapper = (QueryWrapper<ZcAssetImageEntity>) zcAssetImageObj;
                    zcAssetImageNum++;
                }
                Object zcAssetInfoObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetInfoQueryWrapper, zcAssetInfoPagination.getMenuId(), "zc_asset_info"));
                if (ObjectUtil.isEmpty(zcAssetInfoObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetInfoQueryWrapper = (QueryWrapper<ZcAssetInfoEntity>) zcAssetInfoObj;
                    zcAssetInfoNum++;
                }
                Object zcAssetWarrantObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetWarrantQueryWrapper, zcAssetInfoPagination.getMenuId(), "zc_asset_warrant"));
                if (ObjectUtil.isEmpty(zcAssetWarrantObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetWarrantQueryWrapper = (QueryWrapper<ZcAssetWarrantEntity>) zcAssetWarrantObj;
                    zcAssetWarrantNum++;
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcAssetAreaObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetAreaQueryWrapper, zcAssetInfoPagination.getMenuId(), "zcAssetArea"));
                if (ObjectUtil.isEmpty(zcAssetAreaObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetAreaQueryWrapper = (QueryWrapper<ZcAssetAreaEntity>) zcAssetAreaObj;
                    zcAssetAreaNum++;
                }
                Object zcAssetImageObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetImageQueryWrapper, zcAssetInfoPagination.getMenuId(), "zcAssetImage"));
                if (ObjectUtil.isEmpty(zcAssetImageObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetImageQueryWrapper = (QueryWrapper<ZcAssetImageEntity>) zcAssetImageObj;
                    zcAssetImageNum++;
                }
                Object zcAssetInfoObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetInfoQueryWrapper, zcAssetInfoPagination.getMenuId(), "zcAssetInfo"));
                if (ObjectUtil.isEmpty(zcAssetInfoObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetInfoQueryWrapper = (QueryWrapper<ZcAssetInfoEntity>) zcAssetInfoObj;
                    zcAssetInfoNum++;
                }
                Object zcAssetWarrantObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetWarrantQueryWrapper, zcAssetInfoPagination.getMenuId(), "zcAssetWarrant"));
                if (ObjectUtil.isEmpty(zcAssetWarrantObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetWarrantQueryWrapper = (QueryWrapper<ZcAssetWarrantEntity>) zcAssetWarrantObj;
                    zcAssetWarrantNum++;
                }
            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getJnpf_zc_asset_warrant_jnpf_code())) {
                zcAssetWarrantNum++;
                zcAssetWarrantQueryWrapper.lambda().like(ZcAssetWarrantEntity::getCode, zcAssetInfoPagination.getJnpf_zc_asset_warrant_jnpf_code());
            }

            if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getJnpf_zc_asset_warrant_jnpf_certifiedAddress())) {
                zcAssetWarrantNum++;
                zcAssetWarrantQueryWrapper.lambda().like(ZcAssetWarrantEntity::getCertifiedAddress, zcAssetInfoPagination.getJnpf_zc_asset_warrant_jnpf_certifiedAddress());
            }

            if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getAssetCode())) {
                zcAssetInfoNum++;
                zcAssetInfoQueryWrapper.lambda().like(ZcAssetInfoEntity::getAssetCode, zcAssetInfoPagination.getAssetCode());
            }

            if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getAssetName())) {
                zcAssetInfoNum++;
                zcAssetInfoQueryWrapper.lambda().like(ZcAssetInfoEntity::getAssetName, zcAssetInfoPagination.getAssetName());
            }

            if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getAssetNature())) {
                zcAssetInfoNum++;
                zcAssetInfoQueryWrapper.lambda().eq(ZcAssetInfoEntity::getAssetNature, zcAssetInfoPagination.getAssetNature());
            }

            if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getAssetUse())) {
                zcAssetInfoNum++;
                zcAssetInfoQueryWrapper.lambda().eq(ZcAssetInfoEntity::getAssetUse, zcAssetInfoPagination.getAssetUse());
            }

            if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getAssetSource())) {
                zcAssetInfoNum++;
                zcAssetInfoQueryWrapper.lambda().eq(ZcAssetInfoEntity::getAssetSource, zcAssetInfoPagination.getAssetSource());
            }

            if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getPropertyRightUnit())) {
                zcAssetInfoNum++;
                zcAssetInfoQueryWrapper.lambda().eq(ZcAssetInfoEntity::getPropertyRightUnit, zcAssetInfoPagination.getPropertyRightUnit());
            }

            if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getManagementUnit())) {
                zcAssetInfoNum++;
                zcAssetInfoQueryWrapper.lambda().eq(ZcAssetInfoEntity::getManagementUnit, zcAssetInfoPagination.getManagementUnit());
            }

            if (ObjectUtil.isNotEmpty(zcAssetInfoPagination.getDetailedAddress())) {
                zcAssetInfoNum++;
                zcAssetInfoQueryWrapper.lambda().like(ZcAssetInfoEntity::getDetailedAddress, zcAssetInfoPagination.getDetailedAddress());
            }

        }
        if (zcAssetAreaNum > 0) {
            List<String> zcAssetAreaIdList = zcAssetAreaService.list(zcAssetAreaQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getAssetId())).map(t -> t.getAssetId()).collect(Collectors.toList());
            long count = zcAssetAreaService.count();
            if (count > 0) {
                intersectionList.add(zcAssetAreaIdList);
            }
            AllIdList.addAll(zcAssetAreaIdList);
        }
        total += zcAssetAreaNum;
        if (zcAssetImageNum > 0) {
            List<String> zcAssetImageIdList = zcAssetImageService.list(zcAssetImageQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getAssetId())).map(t -> t.getAssetId()).collect(Collectors.toList());
            long count = zcAssetImageService.count();
            if (count > 0) {
                intersectionList.add(zcAssetImageIdList);
            }
            AllIdList.addAll(zcAssetImageIdList);
        }
        total += zcAssetImageNum;
        if (zcAssetWarrantNum > 0) {
            List<String> zcAssetWarrantIdList = zcAssetWarrantService.list(zcAssetWarrantQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getAssetId())).map(t -> t.getAssetId()).collect(Collectors.toList());
            long count = zcAssetWarrantService.count();
            if (count > 0) {
                intersectionList.add(zcAssetWarrantIdList);
            }
            AllIdList.addAll(zcAssetWarrantIdList);
        }
        total += zcAssetWarrantNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            zcAssetInfoQueryWrapper.lambda().in(ZcAssetInfoEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            zcAssetInfoQueryWrapper.lambda().and(t -> t.in(ZcAssetInfoEntity::getId, finalAllSuperIDlist));
        }

        //排序
        if (StringUtil.isEmpty(zcAssetInfoPagination.getSidx())) {
            zcAssetInfoQueryWrapper.lambda().orderByDesc(ZcAssetInfoEntity::getAssetCode);
        } else {
            try {
                String sidx = zcAssetInfoPagination.getSidx();
                ZcAssetInfoEntity zcAssetInfoEntity = new ZcAssetInfoEntity();
                Field declaredField = zcAssetInfoEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                zcAssetInfoQueryWrapper = "asc".equals(zcAssetInfoPagination.getSort().toLowerCase()) ? zcAssetInfoQueryWrapper.orderByAsc(value) : zcAssetInfoQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<ZcAssetInfoEntity> page = new Page<>(zcAssetInfoPagination.getCurrentPage(), zcAssetInfoPagination.getPageSize());
                IPage<ZcAssetInfoEntity> userIPage = this.page(page, zcAssetInfoQueryWrapper);
                return zcAssetInfoPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<ZcAssetInfoEntity> list = new ArrayList();
                return zcAssetInfoPagination.setData(list, list.size());
            }
        } else {
            return this.list(zcAssetInfoQueryWrapper);
        }
    }

    @Override
    public ZcAssetInfoEntity getInfo(String id) {
        QueryWrapper<ZcAssetInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcAssetInfoEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcAssetInfoEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcAssetInfoEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(ZcAssetInfoEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法
    @Override
    public ZcAssetWarrantEntity getZcAssetWarrant(String id) {
        QueryWrapper<ZcAssetWarrantEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcAssetWarrantEntity::getAssetId, id);
        queryWrapper.last("LIMIT 1");
        return zcAssetWarrantService.getOne(queryWrapper);
    }

    @Override
    public ZcAssetAreaEntity getZcAssetArea(String id) {
        QueryWrapper<ZcAssetAreaEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcAssetAreaEntity::getAssetId, id);
        queryWrapper.last("LIMIT 1");
        return zcAssetAreaService.getOne(queryWrapper);
    }

    @Override
    public ZcAssetImageEntity getZcAssetImage(String id) {
        QueryWrapper<ZcAssetImageEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcAssetImageEntity::getAssetId, id);
        queryWrapper.last("LIMIT 1");
        return zcAssetImageService.getOne(queryWrapper);
    }    //验证表单唯一字段

    @Override
    public boolean checkForm(ZcAssetInfoForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        if (isUp) {
            id = form.getId();
        }
        if (ObjectUtil.isNotEmpty(form.getAssetName())) {
            QueryWrapper<ZcAssetInfoEntity> assetNameWrapper = new QueryWrapper<>();
            assetNameWrapper.lambda().eq(ZcAssetInfoEntity::getAssetName, form.getAssetName());
            if (isUp) {
                assetNameWrapper.lambda().ne(ZcAssetInfoEntity::getId, id);
            }
            if ((int) this.count(assetNameWrapper) > 0) {
                total++;
            }
        }
        if (ObjectUtil.isNotEmpty(form.getZc_asset_warrant())) {
        }
        if (ObjectUtil.isNotEmpty(form.getZc_asset_area())) {
        }
        if (ObjectUtil.isNotEmpty(form.getZc_asset_image())) {
        }
        if (total > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<DictionaryTypeSelectVO> selectSelectorList(ZcAssetInfoEntity entity) {
        return baseMapper.selectSelectorList(entity);
    }

}
